<style scoped>
  .app-container >>> .scode {
    cursor: pointer;
    color: #20B2AA;
    text-decoration: underline;
  }
  .app-container >>> .scodeth {
    color: #515a6e;
  }
</style>
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="采购类型" prop="typeName">
        <el-select v-model="queryParams.type" clearable filterable placeholder="请选择采购类型" size="small">
          <el-option
            v-for="dict in types"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="statusname">
        <el-select v-model="queryParams.status" clearable filterable placeholder="请选择状态" size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购主体" prop="orgId">
        <el-select v-model="queryParams.orgId" filterable clearable placeholder="请选择采购主体" clearable size="small">
          <el-option
            v-for="dict in orgs"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
            @click.native="getStore($event, dict)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库房" prop="strmId">
        <el-select v-model="queryParams.strmId" clearable filterable placeholder="请选择库房" size="small">
          <el-option
              v-for="item in roomOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="departid">
        <el-select v-model="queryParams.departid" clearable filterable placeholder="请选择部门" size="small">
          <el-option
              v-for="item in departOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierid">
        <el-select v-model="queryParams.supplierid" filterable clearable placeholder="请选择供应商" size="small">
          <el-option
            v-for="item in suppliers"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="采购时间" prop="startdate">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.startdate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期">
            </el-date-picker>
            <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.enddate" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期">
            </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['harvest:freightorder:export']"
        >导出</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-printer"-->
<!--          size="mini"-->
<!--          :disabled="ids.length != 1"-->
<!--          @click="handleWhinformExport"-->
<!--        >打印入库单</el-button>-->
<!--      </el-col>-->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="listData" :span-method="objectSpanMethod" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="code" label-class-name="scodeth" class-name="scode" width="100">
<!--        <template slot-scope="scope">-->
<!--          <span @click="viewIt(itemData4[11])">{{ itemData4[0] }}</span>-->
<!--        </template>-->

        <template slot-scope="scope">
          <span @click="viewIt(scope.row.id)">{{ scope.row.code }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="采购日期" align="center" prop="orgName" >-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.row.purchdate.substr(0, 10) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="入库库房" align="center" prop="srname" width="140" />
<!--      <el-table-column label="部门" align="center" prop="department" width="140"/>-->
      <el-table-column label="采购主体" align="center" prop="orgname" width="140" >
        <template slot-scope="scope">
          <span>{{ scope.row.orgname + ' ' + scope.row.department }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplier" width="140" />
      <el-table-column label="产品" align="center" prop="productname" width="140"/>
      <el-table-column label="规格" align="center" prop="spname" width="140"/>
      <el-table-column label="单价" align="center" prop="price"/>
      <el-table-column label="数量" align="center" prop="count" />
      <el-table-column label="金额(元)" align="center" prop="amount" >
        <template slot-scope="scope">
          <span>{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款状态" align="center" prop="payStatusName" />
      <el-table-column label="采购类型" align="center" prop="typeName"/>
      <el-table-column label="状态" align="center" prop="statusname" />
      <el-table-column label="提交人" align="center" prop="operator" />
      <el-table-column label="创建时间" align="center" prop="createtime" />
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['harvest:freightorder:edit']"
          >修改</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listPurchasebill, getPurchasebill, delPurchasebill, addPurchasebill, updatePurchasebill, exportPurchasebill } from "@/api/purchase/purchase";
import { findStoreroom,getDepartmentList,findStoreroomListByPermiss } from "@/api/public";
import { getContracts } from "@/api/harvest/procurementcontract";
import { findSupploerlist, findOrganizationList } from "@/api/public";
import { listData } from '@/api/system/dict/data'

export default {
  name: "Purchasebill",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      guids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      ids: [],
      // 总条数
      total: 0,
      // 采购单表格数据
      listData: [

      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        functionType: 26,
        pageNum: 1,
        pageSize: 10,
        paystatus: null,
        status: null,
        storeroomcode: null,
        startdate: null,
        enddate: null,
        insrenddate: null,
        contractid: null,
        departid: null,
        payStatusList: null,
        strmId:null,
        orgId:null,
        supplierid: null,
        type:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      roomOptions: [],
      departOptions: [],
      contractOptions: [],
      statusOptions: [],
      suppliers: [],
      orgs: [],
      types:[],
      totalNum: '',
      totalWeight: '',
      totalHweight: '',
      totalSettlement: '',
      printUrl: 'http://testadmin.tudouji.com.cn:8095/RDP-SERVER/rdppage/main/a3138b35bca80f8844b950bfd7f3e480?focode='
    };
  },
  created() {
    // this.queryParams.startdate = this.getMonthFirDate();
    this.getList();
    // this.findStoreroom();
    this.getDepartmentList();
    this.getDicts("purchase_status").then(response => {
      this.statusOptions = response.data;
    });
    //查询采购类型
    this.getDicts("purchasebill_type").then(response=>{
      this.types=response.data;
      console.log(this.types);
    });

    //查询组织
    findOrganizationList().then(response => {
      this.orgs = response.data;
    });
    //查询供应商
    findSupploerlist({}).then(response => {
      this.suppliers = response.data;
    });
  },
  methods: {
    getStore(event, item){
      findStoreroomListByPermiss({orgguid: item.guid,functionType: 10}).then(response => {
        this.roomOptions = response.data;
      });
    },
    sumIt(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        // index 第几列从0开始
        if (index === 1) {
          sums[1] = `合计(${this.totalNum}条)`;
          return;
        }
        if (index === 8) {
          sums[index] = this.totalWeight;
          return;
        }
        if (index === 10) {
          sums[index] = this.totalHweight;
          return;
        }
        if (index === 12) {
          sums[index] = this.totalSettlement;
          return;
        }
        sums[index] = '-';
      });
      return sums;
    },
    viewIt(id) {
      this.$router.push({path: '/purchase/purchaseinfo', query: {id: id}});

      // this.$router.push({
      //   name:'purchaseinfo',
      //   // path:'/purchase/purchaseinfo',
      //   query:{
      //     id:id
      //   }
      // },
      // )

      // let postData=this.$router.push({
      //     name:'purchaseinfo',
      //     query:{
      //       id:id
      //     }
      //   },
      // )
      // window.open(postData.href,"_blank");

    },
    getDepartmentList(){
      getDepartmentList().then(response => {
        this.departOptions = response.data;
      });
    },
    findStoreroom(){
       findStoreroom().then(response => {
        this.roomOptions = response.data;
      });
    },
    /** 查询采购单列表 */
    getList() {
      // console.log(this.queryParams)
      this.loading = true;
      listPurchasebill(this.queryParams).then(response => {
        this.listData = response.rows;
        this.total = response.total;
        this.totalNum = response.num;
        this.totalWeight = response.weight;
        this.totalHweight = response.hweight;
        this.totalSettlement = response.settlement;
        this.loading = false;
        this.gatherTableData();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        autoid: null,
        guid: null,
        ordercode: null,
        code: null,
        batchcode: null,
        batchid: null,
        plantorid: null,
        plantor: null,
        plantorphone: null,
        drivername: null,
        driverphone: null,
        provence: null,
        city: null,
        country: null,
        street: null,
        carcode: null,
        amount: null,
        arealandid: null,
        arealand: null,
        variety: null,
        productinfoid: null,
        weight: null,
        price: null,
        settlement: null,
        harvest: null,
        storeroomcode: null,
        storeroom: null,
        storehousecode: null,
        storehouse: null,
        createtime: null,
        status: 0,
        operatorid: null,
        lastupdate: null,
        remark: null,
        unloadtime: null,
        qatype: null,
        specification: null,
        specificationid: null,
        spotcheckrate: null,
        discountrate: null,
        soilchkrate: null,
        unqualifiedchkrate: null,
        deducttype: null,
        setlwgtype: null,
        contractid: '',
        hweight: null,
        organizationid: null,
        paystatus: 0,
        pkgwght: null,
        rweight: null,
        hrweight: null,
        wghtperpkg: null,
        pkgcount: null,
        unprocdAmount: null,
        isdiscount: null,
        latitude: null,
        longitude: null,
        distance: null,
        spguid: null,
        actualsettl: null,
        departid: null,
        department: null,
        flowid: null,
        strguid: null,
        refuseflag: null,
        operator: null,
        acceptstatus: 0,
        ratend: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.guids = selection.map(item => item.guid);
      this.ids=selection.map(item=>item.id);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.open = true;
      // this.title = "添加采购单";
      this.$router.push("/purchase/addPurchaseInfo",)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log("ids:---",this.ids)
      let id=this.ids[0];
      this.$router.push({ path:'/purchase/addPurchaseInfo', query: { purchaseId: id } })

      // this.reset();
      // const autoid = row.autoid || this.ids
      // getPurchasebill(autoid).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改采购单";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.autoid != null) {
            updatePurchasebill(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchasebill(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const autoids = row.autoid || this.guids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPurchasebill(autoids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      let that = this;
      let par = that.queryParams;
      this.$confirm('是否确认导出所有采购单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPurchasebill(par);
        }).then(response => {
          that.download(response.msg);
        })
    },
    /** 导出入库单按钮操作 */
    handleWhinformExport() {
      let that = this;
      const autoid = this.guids[0];
      if (autoid) {
        window.open(that.printUrl + autoid, "_blank", "toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
      }
    },
    myPrint() {
      window.open("", "_blank", "toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
      var win =window.opener;
        // win.document.write(`<iframe name='${title}' src='${url}' style="position: absolute;border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;"></iframe>`);
      win.document.title = '你好';
      let subOutputRankPrint = document.createElement("div");
      subOutputRankPrint.innerHTML = 1111111111111;
      subOutputRankPrint.className = 'test';
      win.document.body.append(subOutputRankPrint)
      // window.open("_blank");
      // // 1. 设置要打印的区域 div的className
      // let subOutputRankPrint = document.createElement("div");
      // subOutputRankPrint.innerHTML = 1111111111111;
      // document.body.appendChild(subOutputRankPrint)
      // // 2. 设置页面比例
      // document.getElementsByTagName("body")[0].style.zoom = 0.68;
      // window.print();
      // // 3. 还原：将旧的页面储存起来，当打印完成后返给给页面
      // window.location.reload();
    },


    // 获取相同编号的订单
    gatherTableData() {
      let OrderObj = {}
      this.listData.forEach((element, index) => {
        element.rowIndex = index
        if (OrderObj[element.code]) {
          OrderObj[element.code].push(index)
        } else {
          OrderObj[element.code] = []
          OrderObj[element.code].push(index)
        }
      })

      // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
      this.OrderIndexArr = [];
      for (let k in OrderObj) {
        if (OrderObj[k].length > 1) {
          this.OrderIndexArr.push(OrderObj[k])
        }
      }
    },

    //0-15
    // 合并单元格
    objectSpanMethod({row,column,rowIndex,columnIndex}) {
      let colIndexs = [0,1,2,3,4,5,6,12,13,14,15,16];
        if (colIndexs.indexOf(columnIndex) > -1) {
          if (this.OrderIndexArr && this.OrderIndexArr.length){
          for (let i = 0; i < this.OrderIndexArr.length; i++) {
            let element = this.OrderIndexArr[i]
            for (let j = 0; j < element.length; j++) {
              let item = element[j]
              if (rowIndex == item) {
                if (j == 0) {
                  return {
                    rowspan: element.length,
                    colspan: 1
                  }
                } else if (j != 0) {
                  return {
                    rowspan: 0,
                    colspan: 0
                  }
                }
              }
            }
          }
        }
      }
    },
  },


};
</script>
